package Aleehot100;

/**
 * ClassName: c095
 * Package: Aleehot100
 * Description:72. 编辑距离
 *
 * @Author BCXJ
 * @Create 2025/9/15 08:41
 * @Version 1.0
 * @Since 1.0
 */
public class c095 {
    public static void main(String[] args) {
        System.out.println(minDistance("horse", "ros"));
    }


    public static int minDistance(String word1, String word2) {
        // 长度初始化
        int r = word1.length();
        int c = word2.length();
        // 初始化dp
        int[][] dp = new int[r + 1][c + 1];
        for (int i = 0; i <= c; i++) {
            dp[0][i] = i;
        }
        for (int i = 0; i <= r; i++) {
            dp[i][0] = i;
        }
        // 按行进行dp的求解
        for (int i = 1; i <= r; i++) {
            for (int j = 1; j <= c; j++) {
                // 匹配
                if(word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    // 不匹配
                    dp[i][j] = Math.min(dp[i - 1][j - 1] + 1,  // 替换
                            Math.min(dp[i - 1][j] + 1, // 删除
                                    dp[i][j - 1] + 1)); // 插入
                }
            }
        }
        return dp[r][c];
    }
}